﻿using Newtonsoft.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using Vulild.AopDecoration;
using Vulild.AopDecoration.Test;

AopDecorationGenerator aop = new AopDecorationGenerator();

var type = aop.GenerateType<ITest, Test>();

var ins = Activator.CreateInstance(type, new object[] { "vulild", 19901017 });
if (ins is IAopDecoration<ITest> filterAop)
{
    var filter = new TestFilter();
    //filterAop.ExecutingFilters.Add(filter);
    filterAop.ExecutedFilters.Add(filter);
    var exFilter = new TestExceptionFilter();
    filterAop.ExceptionFilters.Add(exFilter);
}
if (ins is ITest test)
{
    int testint = 1;
    string teststring = test.ToString();
    int str = test.TestString(teststring);
    test.TestInt(ref testint);
    test.Vulild(1);
    test.TestDelgate += test =>
    {
        Console.WriteLine($"委托：{test}");
    };
    test.TestDelgateEvent += Test_TestDelgateEvent; ;
    test.Say("调用函数：hello");
    test.TestSay<Test, ITest>(test as Test, "泛型函数：TestSay");
    test.FieldTest = "属性赋值：456";
    test.TestTest = new Test("构造函数", 5);
    test.TestTest.FieldTest = "被包装对象属性赋值：TestTest.FieldTest";
}
Console.ReadLine();

void Test_TestDelgateEvent(string test)
{
    Console.WriteLine($"事件：{test}");
}

public class TestFilter : IAopFilter
{
    public void Execute<T>(AopContext<T> context)
    {
        Console.WriteLine($"方法名：{context.MemberName}");
        Console.WriteLine($"参数：{Environment.NewLine}");
        foreach (var kv in context.Params)
        {
            Console.WriteLine($"{kv.Key}:{kv.Value}{Environment.NewLine}");
        }

        Console.WriteLine($"执行结果：{Environment.NewLine}");
        if (context.Result != null)
        {
            if (context.Result.GetType().IsValueType)
            {
                Console.WriteLine(context.Result);
            }
            else
            {
                Console.WriteLine(JsonConvert.SerializeObject(context.Result));
            }
        }
    }
}

public class TestExceptionFilter : IAopFilter
{
    public void Execute<T>(AopContext<T> context)
    {
        Console.WriteLine("异常");
        Console.WriteLine(context?.Exception?.ToString());
    }
}